package org.bai.miaoshaproject.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bai.miaoshaproject.common.Const;
import org.bai.miaoshaproject.controller.viewobject.UserVO;
import org.bai.miaoshaproject.error.BusinessException;
import org.bai.miaoshaproject.error.EmBusinessError;
import org.bai.miaoshaproject.response.CommonReturnType;
import org.bai.miaoshaproject.service.UserService;
import org.bai.miaoshaproject.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;

/**
 * ClassName UserController
 *
 * @author Bai
 * @version 1.0
 * @date 2019/5/26 0026 下午 22:51
 **/

@Slf4j
@RestController
@CrossOrigin(allowCredentials = "true", origins = {"*"})
@RequestMapping(value = "/user")
public class UserController {

    private final UserService userService;

    private final HttpServletRequest httpServletRequest;

    @Autowired
    public UserController(UserService userService, HttpServletRequest httpServletRequest) {
        this.userService = userService;
        this.httpServletRequest = httpServletRequest;
    }

    @PostMapping(value = "/login", consumes = {Const.CONTENT_TYPE_FORMED})
    public CommonReturnType login(
            @RequestParam(name = "telphone")String telphone,
            @RequestParam(name = "password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {

        // 校验参数
        if(StringUtils.isEmpty(telphone) || StringUtils.isEmpty(password)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        UserModel userModel = userService.validateLogin(telphone, this.encodeByMD5(password));
        this.httpServletRequest.getSession().setAttribute(Const.IS_LOGIN, true);
        this.httpServletRequest.getSession().setAttribute(Const.LOGIN_USER, userModel);
        return CommonReturnType.creatSuccess();
    }

    @PostMapping(value = "/register", consumes = {Const.CONTENT_TYPE_FORMED})
    public CommonReturnType register(
            @RequestParam(name = "telphone") String telphone,
            @RequestParam(name = "otpCode") String otpCode,
            @RequestParam(name = "name") String name,
            @RequestParam(name = "gender") Integer gender,
            @RequestParam(name = "age") Integer age,
            @RequestParam(name = "password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        String inSessionOtpCode = (String)this.httpServletRequest.getSession().getAttribute(telphone);
        if(!StringUtils.equals(otpCode, inSessionOtpCode)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符");
        }
        // 用户注册
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrprPassword(encodeByMD5(password));
        userService.register(userModel);
        return CommonReturnType.creatSuccess();
    }

    public String encodeByMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String newstr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    @PostMapping(value = "getOtp", consumes = Const.CONTENT_TYPE_FORMED)
    public CommonReturnType getOtp(
            @RequestParam(name = "telphone") String telphone){
        // 按照规则生成OTP验证码
        int randomInt = ThreadLocalRandom.current().nextInt(89999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);

        //将OTP验证码和用户对应的手机号码相关联,使用HttpSession保存
        httpServletRequest.getSession().setAttribute(telphone, otpCode);
        log.info("OPT验证码输出 telphone：{}  opt：{}", telphone, otpCode);

        // 将OTP的验证码发送到手机上

        return  CommonReturnType.creatSuccess();
    }

    @GetMapping(value = "get/{id}")
    public CommonReturnType<UserVO> getUser(
            @PathVariable(value = "id") Integer id) throws BusinessException {
        // 通过调用Service的服务获取对应的用户ID并返回给前端
        UserModel userModel = userService.getUserById(id);

        if(userModel == null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        // 将核心领域模型用户对象转换为可供UI使用的viewObject
        return CommonReturnType.creatSuccess(convertFromModel(userModel));
    }

    private UserVO convertFromModel(UserModel userModel){
        if(userModel == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }
}
